package it.i118.jindice;

/**
 * Created with IntelliJ IDEA.
 * User: sciovante
 * Date: 28/03/13
 * Time: 10.33
 */

public abstract class DataAccessObject<T extends DataObject> {

    protected final int NO_LIMIT = -1;
    private final Class<T> table;
    private final Jindice jindice;

    protected DataAccessObject(Class<T> table) {
        this.jindice = Jindice.getInstance();
        this.table = table;
    }

    Class<T> getTable() {
        return table;
    }

    public int count() {
        return jindice.count(table);
    }

    public int deleteAll(DataObjectFilter<T> filter) {
        return jindice.deleteAll(table, filter);
    }

    public boolean exist(long id) {
        return jindice.exist(table, id);
    }

    public boolean deleteById(long id) {
        return jindice.delete(table, id);
    }

    public void deleteAll() {
        jindice.deleteAll(table);
    }

    public void insert(T dataObject) {
        jindice.save(dataObject);
    }

    public T getById(long id) {
        return (T) jindice.load(table, id);
    }

    public T[] getAll() {
        return getAll(null, NO_LIMIT);
    }

    public T[] getAll(int limit) {
        return getAll(null, limit);
    }

    public T[] getAll(DataObjectFilter<T> filter) {
        return getAll(filter, NO_LIMIT);
    }

    public T[] getAll(DataObjectFilter<T> filter, int limit) {
        return (T[]) jindice.getAll(table, filter, limit);
    }

    public T getFirst(DataObjectFilter<T> filter) {
        T[] lov = getAll(filter, 1);
        return (lov.length == 0) ? null : lov[0];
    }

    protected T[] getByIndex(String key, String index) {
        return (T[]) jindice.getByIndex(table, index, key, null, NO_LIMIT);
    }

    protected T[] getByIndex(String key, String index, int limit) {
        return (T[]) jindice.getByIndex(table, index, key, null, limit);
    }

    protected T[] getByIndex(String key, String index, DataObjectFilter<T> filter) {
        return (T[]) jindice.getByIndex(table, index, key, filter, NO_LIMIT);
    }

    protected T[] getByIndex(String key, String index, DataObjectFilter<T> filter, int limit) {
        return (T[]) jindice.getByIndex(table, index, key, filter, limit);
    }

    public String[] getIndexKeys(String indexName) {
        return jindice.getIndexKeys(table, indexName);
    }
}
